package cn.jiemusic.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.jiemusic.common.CustomException;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class TransferUtils {

    public static void upload(MultipartFile file, String fileName, Long id, String type) {

        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isEmpty(originalFilename)) {
            throw new CustomException("传输失败");
        }

        // 创建目录
        File uploadDirFile = new File(fileName + File.separator + id);
        FileUtil.mkdir(uploadDirFile); // 确保目录存在

        // 获取文件扩展名
        String fileExtension = FileUtil.extName(originalFilename);
        if (StrUtil.isEmpty(fileExtension)) {
            throw new CustomException("文件格式错误");
        }

        // 生成新的文件名
        String newFileName = type + "." + fileExtension;

        // 存储路径
        File destFile = new File(uploadDirFile, newFileName);

        try (InputStream inputStream = file.getInputStream()) {
            // 使用 Hutool 将文件保存到指定路径
            FileUtil.writeFromStream(inputStream, destFile);
        } catch (IOException e) {
            throw new CustomException("文件存储失败");
        }

    }
    // 上传封面图像的方法
    public static void uploadCover(byte[] coverData, String fileName, Long mid) {
        try {
            // 将 byte[] 转换为 InputStream
            InputStream inputStream = new ByteArrayInputStream(coverData);

            String path = fileName + File.separator + mid + File.separator + "cover.jpg";
            // 使用 Hutool 将文件保存到指定路径
            FileUtil.writeFromStream(inputStream, path);

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public static String getAPathById(String path, String id, String type) {
        if (type.equals("audio"))
            return path + File.separator + id + File.separator + "audio.mp3";
        else if (type.equals("cover"))
            return path + File.separator + id + File.separator + "cover.jpg";
        else return path;
    }
}
